/**
 * Created by 61741 on 2018/1/21.
 */
var dt;
var scope = "LOGISTICS";
var shopId = userId;
$(function () {
    dt = $("#mainTable").dataTable({
        fnDrawCallback: function () {
            $("img[data-src]").each(function () {
                $(this).attr("src", $(this).attr("data-src"));
            })
        }
    });
    loadShop();
    loadArticle("",true);
    loadGoodChosen();
    loadCarouselList();
    loadFlagGood("SHOP_DISCOUNT");
    $("#city,#goodAreaSelect,#shopAreaSelect,select[name='filterCity']").chosen({
        width: 200,
        height: 33,
        "no_results_text": "未找到对应的区域"
    });
    filterContentByCity();
    loadbrandFlag();

})
var GOOD_CACHE = {};
var CURRENT_TARGET_GOOD_LIST;
var SHOP_GOOD_CACHE = {};
function addCarousel() {
    var data = {
        uri: $("#uri").val() || "",
        type: $("#type").val() || "",
        shopId:shopId||"",
    };

    if (data["type"] == "LINK") {
        data["typeValue"] = $("#linkInput").val()
    } else if (data["type"] == "GOOD") {
        data["typeValue"] = $("#goodSelect").val()
    } else if (data["type"] == "ARTICLE") {
        data["typeValue"] = $("#articleSelect").val()
    }
    if (isEmpty(data["uri"])) {
        bootbox.alert("轮播图片不能为空!");
        return -1;
    }
    asyncAjax({
        url: ctx + "/shop/carousel/add?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0"){
                $("#addDialog").modal("hide");
                var htmlArray = [];
                var tds = $("#carouselTmpl").tmpl(res["data"]).find("td");
                $.each(tds, function (idx, el) {
                    htmlArray.push($(el).html());
                })

                dt.fnAddData([htmlArray]);
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}

function loadCarouselList() {
    var data = {
        shopId:shopId
    };
    asyncAjax({
        url: ctx + "/shop/carousel/list/?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        beforeSend: function (req) {
            dt.fnClearTable();
        },
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                var dataArray = [];
                $.each(res["data"], function (idx, carousel) {
                    var htmlArray = [];
                    var tds = $("#carouselTmpl").tmpl(carousel).find("td");
                    $.each(tds, function (idx, el) {
                        htmlArray.push($(el).html());
                    })
                    dataArray.push(htmlArray);
                })
                if (dataArray.length > 0) {
                    dt.fnAddData(dataArray);
                }

            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}

function delCarousel(cid) {
    bootbox.confirm({
        title: '提示',
        message: '确定删除此轮播图么？',
        buttons: {
            confirm: {
                label: "确定"
            },
            cancel: {
                label: '取消'
            }
        },
        callback: function (res) {
            if (res == true) {
                var data = {cid: cid};
                asyncAjax({
                    url: ctx + "/shop/carousel/del?" + $.param(data).replace(/(%5D|%5B)/g, ""),
                    success: function (res) {
                        console.log("res:%o", res);
                        if (res["result"] == "0") {
                            loadCarouselList();
                        } else {
                            bootbox.alert(res["msg"]);
                        }
                    }
                })
            }
        }
    })

}
function changeValueShow() {
    var type = $("#type").val();
    switch (type) {
        case "LINK":
            $("#goodSelectBox,#articleSelectBox").hide("slow", function () {
                $("#linkInputBox").show("slow");
            });
            break;
        case "GOOD":
            $("#linkInputBox,#articleSelectBox").hide("slow", function () {
                $("#goodSelectBox").show("slow");
            });
            break;

        case "ARTICLE":
            $("#goodSelectBox,#linkInputBox").hide("slow", function () {
                $("#articleSelectBox").show("slow");
            });
            break;

    }
}

function loadShop() {
    var data = {reviewStatus: 2};
    asyncAjax({
        url: ctx + "/user/mgr/list/99?" + $.param(data).replace(/(%5D|%5B)/g, ""),//行业打牌默认配置厂商
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                $.each(res["data"], function (idx, shopUser) {
                    $(".shopSelect,#goodMerchantSelector,#carouselShopSelect,#newgoodShopSelect").append("<option value='" + shopUser.id + "'>" + shopUser.companyName + "</option>");
                })
                $(".shopSelect,#goodMerchantSelector,#carouselShopSelect,#newgoodShopSelect").chosen({width: 380});
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}

function flagShop(action, shopId) {
    shopId = shopId || $("#shopSelect").val().toString();

    if ("DELETE" == action) {
        bootbox.confirm({
            title: "移除商铺",
            message: "确定将此商铺从首页推广列表中移除么？",
            buttons: {
                confirm: {
                    label: "确定"
                },
                cancel: {
                    label: "取消"
                }
            },
            callback: function (re) {
                if (re == true) {
                    doFlag(shopId, action);
                }
            }
        })
    } else {
        doFlag(shopId, action);
    }

}

function doFlag(shopId, action) {
    var data = {shopId: shopId, action: action, city:"default", pageType: scope};
    asyncAjax({
        url: ctx + "/portal/config/shop/flag?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                loadFlagShop(scope);
                $("#shopSelectDialog").modal("hide");
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}
function getScopeType(type,el) {
    scope=type;
    $('#shopSelectDialog').modal('show');
}
function getdeleteType(id,flag) {
    scope=flag;
    flagShop('DELETE',id);
}
function loadFlagShop(type) {
    var data = {pageType: type,city:"default"};
    asyncAjax({
        url: ctx + "/portal/shop/flag/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                if(type=="LOGISTICS_HOTSERACH"){
                    $("#hotshopBox").html("");
                }
                if (!isEmpty(res["data"])) {
                    if(type=="LOGISTICS_HOTSERACH"){
                        $("#hotshopItemTmpl").tmpl(res["data"]).appendTo($("#hotshopBox"));
                    }
                } else {

                    if(type=="LOGISTICS_HOTSERACH"){
                        $("#hotshopBox").html("<div class='alert alert-warning'>该模块尚未配置推广商铺</div>");
                    }

                }
            } else {
                bootbox.alert(res["msg"]);

            }
        }
    })
}

function filterContentByCity() {
    $("select[name=\"filterCity\"]").on('change', function (e, param) {
            var value = $(this).val();
            if (isEmpty(value)) {
                $(this).parents(".card").find(".good-item,.shop-item").show();
                return -1;
            }
            $(this).parents(".card").find(".good-item,.shop-item").css("display", "none");
            $(this).parents(".card").find(".good-item[data-city=\"" + value + "\"],.shop-item[data-city=\"" + value + "\"]").show("fast");
            console.log("filter :%o ,target find:%o", value, $(this).parents(".card").find(".card-content .good-item[data-city=\"" + value + "\"],.shop-item[data-city=\"" + value + "\"]"));
        }
    )
}
function loadArticle(pagetype, isFillData) {
    var data = {
        type: 1,
        user_id: shopId
    };
    asyncAjax({
        url: ctx + "/article/getSearchList?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        beforeSend: function (req) {
            $("#pagetype").val('');
            $("#articleSelect").html('');
        },
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                if (!isEmpty(res["data"])) {
                    $.each(res["data"], function (idx, item) {
                        $("#articleSelect").append("<option value=\"" + item["id"] + "\">" + item["main_title"] + "</option>");
                    })

                    $("#articleSelect").chosen({width: 240});
                } else {
                    bootbox.confirm({
                        title: '温馨提示',
                        message: '系统没有资讯数据，如果需要配置资讯请先前往《资讯管理》进行配置.点击"确定"跳转到资讯配置页面！',
                        buttons: {
                            confirm: {
                                label: '确定'
                            },
                            cancel: {
                                label: '取消'
                            }
                        },
                        callback: function (jump) {
                            if (jump) {
                                window.location.href = ctx + "/forum/article";
//                                    $(window.top.document).find('#mainFrame').attr('src',ctx + "/forum/article") ;
                            }
                        }
                    });
                }
            } else {

            }
        },
        complete: function () {
            if (!isFillData) {
                $('#articleSelectDialog').modal('show');
            }
            $("#pagetype").val(pagetype || '');
            if (pagetype == "PORTAL_TOP") {
                $('#picsize').html("图片大小:300px * 186px");
            }
            else if (pagetype == "PORTAL_HOT_TOP") {
                $('#picsize').html("图片大小:290px * 290px");
            }
            else if (pagetype == "PORTAL_HOT_OTH") {
                $('#picsize').html("图片大小:140px * 140px");
            }
        }
    })
}
function loadGoodChosen() {
    var data = {
        status: 1,
        pageNum: 1,
        pageSize: 50000,
        shopId:shopId
    };
    asyncAjax({
        url: ctx + "/goodMgr/good/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            $("#goodSelect,#disgoodSelect").html("");
            if (res["result"] == "0") {
                $.each(res["data"]["goods"], function (id, good) {
                    GOOD_CACHE[good["good_id"]] = good;
                    if (!isEmpty(SHOP_GOOD_CACHE[good["wx_user_id"]])) {
                        SHOP_GOOD_CACHE[good["wx_user_id"]].push(good);
                    } else {
                        SHOP_GOOD_CACHE[good["wx_user_id"]] = [good];
                    }
                    $("#goodSelect,#disgoodSelect").append('<option value=\"' + good["good_id"] + '\">' + good['goodName'] + '</option>')
                })
                $("#goodSelect").chosen({width: 240})
                console.log("good cache:%o", SHOP_GOOD_CACHE);
                $("#addGoodSelect").chosen({width: 380});
                loadGoodInfo();
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}
function loadGoodInfo() {
    $(".target-value[data-type=\"GOOD\"]").each(function (idx, el) {
        var good = GOOD_CACHE[$(this).attr("data-value")];

        $(this).html((good ? good["goodName"] : "<code>关联商品已经失效</code>"));
    })
}
function showShopGood(el) {
    if(userId=='0'){
        shopId=$('#shopselect').val();
        loadShop();
        loadArticle("",true);
        loadGoodChosen();
        loadCarouselList();
        loadFlagGood("SHOP_DISCOUNT");
        loadbrandFlag();
    }

    if ($(el).val() == "0") {
        return -1;
    }
    var target = $(el).attr("data-target");
    $("#" + target).html("<option value=\"\">正在载入</option>");
    $("#" + target).trigger("chosen:updated");

    var data = {
        shopId: $(el).val() || "",
        pageSize: 10000,
        pageNum: 1,
        status: "1"
    };
    asyncAjax({
        url: ctx + "/goodMgr/good/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                var goods = res["data"]["goods"]
                if (isEmpty(goods)) {
                    bootbox.alert("该商店没有商品!");
                    return;
                } else {
                    $("#" + target).html("");
                    $.each(goods, function (idx, good) {
                        $("#" + target).append('<option value=\"' + good["good_id"] + '\">' + good['goodName'] + '</option>')
                    })
                    $("#" + target).trigger("chosen:updated");
                    $("#" + target).chosen();
                }
            } else {
                bootbox.alert(res.msg);
            }
        }
    })
}
function brandflag(name,action) {
    if ("DELETE" == action) {
        bootbox.confirm({
            title: "移除商铺",
            message: "确定将此商铺从首页推广列表中移除么？",
            buttons: {
                confirm: {
                    label: "确定"
                },
                cancel: {
                    label: "取消"
                }
            },
            callback: function (re) {
                if (re == true) {
                    dobrandFlag(name,action);
                }
            }
        })
    } else {
       name=$("#brandNameInput").val()
        dobrandFlag(name,action);
    }
}
function  dobrandFlag(name,action) {
    var data ={brandName:name,brandLogo:$("#url").val(),shopId:shopId}
    asyncAjax({
        url: ctx + "/shop/brandflag/"+action+"?"+$.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                loadbrandFlag();
                $("#brandAddDialog").modal("hide");
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}
function  loadbrandFlag() {
    var data={shopId:shopId}
    asyncAjax({
        url: ctx + "/shop/agencyBrand/list?"+$.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            $("#brandBox").html("");
            console.log("res:%o", res);
            if (res["result"] == "0") {
                if(!isEmpty(res["data"])){
                    $("#brandListTmpl").tmpl(res["data"]).appendTo($("#brandBox"));
                }
                else{
                    $("#brandBox").html("<div class='alert alert-warning'>尚未配置代理品牌</div>");
                }
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })

}
function goodflag(id,action) {
    if ("DELETE" == action) {
        bootbox.confirm({
            title: "移除商铺",
            message: "确定将此商铺从首页推广列表中移除么？",
            buttons: {
                confirm: {
                    label: "确定"
                },
                cancel: {
                    label: "取消"
                }
            },
            callback: function (re) {
                if (re == true) {
                    dogoodflag(id,action);
                }
            }
        })
    } else {
        dogoodflag(id,action);
    }

}
function  dogoodflag(name,action) {
    var data ={goodId:name}
    asyncAjax({
        url: ctx + "/shop/brandflag/"+action+"?"+$.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                loadbrandFlag();
                $("#brandAddDialog").modal("hide");
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}
function  loadgoodflag() {
    asyncAjax({
        url: ctx + "/shop/agencyBrand/list?",
        success: function (res) {
            $("#brandBox").html("");
            console.log("res:%o", res);
            if (res["result"] == "0") {
                if(!isEmpty(res["data"])){
                    $("#brandListTmpl").tmpl(res["data"]).appendTo($("#brandBox"));
                }
                else{
                    $("#brandBox").html("<div class='alert alert-warning'>尚未配置代理品牌</div>");
                }
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })

}
function uploadExcel(fileInputId, prviewElementId, hideValueId, type,_cb) {
    var file = $("#" + fileInputId);
    var previewElement = previewElement!=null?$("#" + prviewElementId):null;
    var val = $("#" + hideValueId);
    if (file == null || file == undefined) {
        alert("文件选择元素ID无效！");
        return;
    }
    if (val == null && val == undefined) {
        alert("返回值存储元素ID无效！");
        return;
    }
    var gp = self.setInterval("getProgress()", 50);
    $.ajaxFileUpload(
        {

            url: ctx+'/user/upload/uplogexcel/'+shopId,
            type: 'post',
            fileElementId: fileInputId,
            dataType: 'application/json',
            async: false,
            success: function (data) {
                console.info("upload response:%o", data);
                data = JSON.parse(data.match(/{.*}/g)[0]);

                window.clearInterval(gp);
                //上传成功返回的信息｛filePath:上传文件后取得的url，result:是否成功，成功为0，失败为-x｝
                if (data.result == "0") {
                    if (previewElement != null && previewElement != undefined) {
                        previewElement.attr("src", "上传成功");
                    }
                    if (val != null && val != undefined) {
                        val.val(data.url);
                        if(typeof _cb=='function'){
                            _cb(data);
                        }
                    }
                } else {
                    alert(data.msg);
                }
                if (typeof callback == "function") {
                    callback();
                }
            },
            error: function (data, status, e) {
                alert("上传失败:" + e);
                window.clearInterval(gp);
            }
        }
    )
}
function getfilename() {
    $(".choose-file").on("change", "input[type='file']", function () {
        var filePath = $(this).val();
        if (filePath.indexOf("xlsx") != -1) {
            var arr = filePath.split('\\');
            var fileName = arr[arr.length - 1];
            $(".showFileName").html(fileName);
        } else {
            $(".showFileName").html("");
            bootbox.alert("请选择正确的文件");
            return false
        }
    })
}
function  discountGood(action,goodId,type) {
    if ("DELETE" == action) {
        bootbox.confirm({
            title: "移除商铺",
            message: "确定将此商铺从首页推广列表中移除么？",
            buttons: {
                confirm: {
                    label: "确定"
                },
                cancel: {
                    label: "取消"
                }
            },
            callback: function (re) {

                if (re == true) {
                    addGood(goodId, action,type);
                }
            }
        })
    } else {
        var newgoodId =$('#'+goodId).val()||'';
        addGood(newgoodId, action,type);
    }

}
 function addGood(goodId, action, type) {
    var data = {goodId: goodId, action: action, goodFlag: type, city: "default"};
    if (isEmpty(data["goodId"])) {
        bootbox.alert("请选择商品!");
        return -1;
    }

    asyncAjax({
        url: ctx + "/portal/config/mark/good/?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                bootbox.alert("操作成功");
                $("#goodAddDialog").modal('hide');
                loadFlagGood(type);
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}
function loadFlagGood(type) {
    var shop_id=shopId||'';
    var data = {city: 'default',shop_id:shop_id};
    asyncAjax({
        url: ctx + "/portal/good/flag/list/" + type + "?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("flag good res:%o", res);
            if (res["result"] == "0") {
                if (isEmpty(res["data"]) || res["data"].length <= 0) {

                    $("#goodBox").html("<label>尚未配置商品</label>");
                    return -1;
                } else {
                    $("#goodBox").html("")
                    $("#discountGoodTmpl").tmpl(res["data"]).appendTo($("#goodBox"));
                }

            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}
